<?php
// 订单自主查询系统 - 后台管理页面
// 版权所有 © 2025 慕念科技. 保留所有权利.

session_start();
require_once '../functions.php';

// 检查是否登录，如果未登录跳转到登录页面
if (!adminLogin()) {
    header('Location: admin_login.php');
    exit;
}

// 获取管理员信息
$adminInfo = getAdminInfo();

// 检查是否有登录失效提示
$loginExpired = isset($_GET['login_expired']) && $_GET['login_expired'] == 1;

// 处理修改管理员信息请求
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['action']) && $_POST['action'] == 'update_admin') {
    $username = trim($_POST['username'] ?? '');
    $currentPassword = trim($_POST['current_password'] ?? '');
    $newPassword = trim($_POST['new_password'] ?? '');
    $confirmPassword = trim($_POST['confirm_password'] ?? '');
    $qq = trim($_POST['admin_qq'] ?? '');
    
    // 验证输入
    if (empty($username)) {
        $error = '用户名不能为空';
    } else {
        // 如果要修改密码，需要验证当前密码
        if (!empty($newPassword)) {
            if (empty($currentPassword)) {
                $error = '请输入当前密码';
            } else if ($newPassword != $confirmPassword) {
                $error = '两次输入的新密码不一致';
            } else {
                // 验证当前密码
                global $pdo;
                $stmt = $pdo->prepare("SELECT password FROM admin_users WHERE id = 1");
                $stmt->execute();
                $dbPassword = $stmt->fetchColumn();
                
                if ($currentPassword != $dbPassword) {
                    $error = '当前密码错误';
                }
            }
        }
        
        // 验证QQ号
        if (!empty($qq) && !is_numeric($qq)) {
            $error = 'QQ号必须是数字';
        }
        
        if (empty($error)) {
            // 准备更新数据
                $updateData = [];
                if (!empty($newPassword)) {
                    $updateData['password'] = $newPassword; // 直接存储明文密码，不加密
                }
                
                // 更新管理员信息
                if (updateAdminInfo($username, $updateData['password'] ?? null, $qq)) {
                $success = '管理员信息更新成功';
                
                // 如果用户名或密码发生变化，强制登出并提示
                if (!empty($updateData['password']) || $username != $adminInfo['username']) {
                    adminLogout();
                    header('Location: admin_login.php?login_expired=1');
                    exit;
                }
                
                // 刷新管理员信息
                $adminInfo = getAdminInfo();
            } else {
                $error = '更新失败，请稍后重试';
            }
        }
    }
}

// 处理登出请求
if (isset($_GET['action']) && $_GET['action'] == 'logout') {
    adminLogout();
    header('Location: admin_login.php');
    exit;
}

// 获取系统设置
$settings = getSystemSettings();

// 处理收件人和快递单号管理
$error = '';
$success = '';
$recipients = getAllRecipients();

// 处理添加收件人
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['action']) && $_POST['action'] == 'add_recipient') {
    $name = trim($_POST['name'] ?? '');
            $phone = trim($_POST['phone'] ?? '');
            $orderNumber = trim($_POST['order_number'] ?? '');
            $trackingNumbers = $_POST['tracking_numbers'] ?? [];
            
            // 验证输入
            if (empty($name) || empty($phone)) {
                $error = '姓名和手机号不能为空';
            } else {
                // 添加收件人
                $recipientId = addRecipient($name, $phone, $orderNumber);
                
                if ($recipientId > 0) {
            // 添加快递单号
            if (!empty($trackingNumbers)) {
                foreach ($trackingNumbers as $trackingNumber) {
                    $trackingNumber = trim($trackingNumber);
                    if (!empty($trackingNumber)) {
                        addTrackingNumber($recipientId, $trackingNumber);
                    }
                }
            }
            $success = '收件人和快递单号添加成功';
            $recipients = getAllRecipients(); // 刷新列表
        } else {
            $error = '添加失败，该收件人信息可能已存在';
        }
    }
}

// 处理删除收件人
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['action']) && $_POST['action'] == 'delete_recipient') {
    $id = intval($_POST['id'] ?? 0);
    
    if ($id > 0 && deleteRecipient($id)) {
        $success = '收件人删除成功';
        $recipients = getAllRecipients(); // 刷新列表
    } else {
        $error = '删除失败，请稍后重试';
    }
}

// 处理删除快递单号
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['action']) && $_POST['action'] == 'delete_tracking') {
    $trackingNumber = trim($_POST['tracking_number'] ?? '');
    
    if (!empty($trackingNumber) && deleteTrackingNumber($trackingNumber)) {
        $success = '快递单号删除成功';
        $recipients = getAllRecipients(); // 刷新列表
    } else {
        $error = '删除失败，请稍后重试';
    }
}

// 处理更新系统设置
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['action']) && $_POST['action'] == 'update_settings') {
    $apiKey = trim($_POST['api_key'] ?? '');
    
    // 处理logo上传
    $logoPath = '';
    if (!empty($_FILES['logo']['name'])) {
        $targetDir = '../uploads/';
        $targetFile = $targetDir . basename($_FILES['logo']['name']);
        $imageFileType = strtolower(pathinfo($targetFile,PATHINFO_EXTENSION));
        
        // 检查文件是否为图片
        $check = getimagesize($_FILES['logo']['tmp_name']);
        if($check !== false) {
            // 允许的文件格式
            if($imageFileType != 'jpg' && $imageFileType != 'png' && $imageFileType != 'gif' && $imageFileType != 'jpeg') {
                $error = '只支持JPG、PNG、GIF格式的图片';
            } else {
                // 创建上传目录
                if (!file_exists($targetDir)) {
                    mkdir($targetDir, 0777, true);
                }
                
                // 为了避免文件覆盖，生成唯一的文件名
                $uniqueId = time() . '_' . mt_rand(1000, 9999);
                $newFileName = $uniqueId . '.' . $imageFileType;
                $targetFilePath = $targetDir . $newFileName;
                
                // 移动上传的文件
                if (move_uploaded_file($_FILES['logo']['tmp_name'], $targetFilePath)) {
                    $logoPath = '/uploads/' . $newFileName;
                    updateSystemSetting('logo', $logoPath);
                } else {
                    $error = 'logo上传失败，请稍后重试';
                }
            }
        } else {
            $error = '上传的文件不是图片';
        }
    }
    
    // 更新联系我们信息
    updateSystemSetting('contact_email', trim($_POST['contact_email'] ?? ''));
    updateSystemSetting('contact_phone', trim($_POST['contact_phone'] ?? ''));
    updateSystemSetting('contact_hours', trim($_POST['contact_hours'] ?? ''));
    
    // 删除隐私政策和服务条款内容（设置为空字符串）
    updateSystemSetting('privacy_policy', '');
    updateSystemSetting('terms_of_service', '');
    
    // 更新API密钥
    if (empty($error) && !empty($apiKey)) {
        if (updateSystemSetting('api_key', $apiKey)) {
            $success = '系统设置更新成功';
            $settings = getSystemSettings(); // 刷新设置
        } else {
            $error = '更新失败，请稍后重试';
        }
    } else if (empty($error) && !empty($logoPath)) {
        $success = 'Logo更新成功';
        $settings = getSystemSettings(); // 刷新设置
    } else if (empty($error)) {
        // 如果没有API密钥或logo更新，但有联系信息等更新
        $success = '系统设置更新成功';
        $settings = getSystemSettings(); // 刷新设置
    }
}

// 处理更改密码
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['action']) && $_POST['action'] == 'change_password') {
    $currentPassword = trim($_POST['current_password'] ?? '');
    $newPassword = trim($_POST['new_password'] ?? '');
    $confirmPassword = trim($_POST['confirm_password'] ?? '');
    
    // 验证输入
    if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
        $error = '所有密码字段都不能为空';
    } else if ($newPassword != $confirmPassword) {
        $error = '两次输入的新密码不一致';
    } else {
        // 验证当前密码
        global $pdo;
        $stmt = $pdo->prepare("SELECT password FROM admin_users WHERE id = 1");
        $stmt->execute();
        $dbPassword = $stmt->fetchColumn();
        
        if ($currentPassword != $dbPassword) {
            $error = '当前密码错误';
        } else {
            // 更新密码
            $stmt = $pdo->prepare("UPDATE admin_users SET password = :password WHERE id = 1");
            if ($stmt->execute([':password' => $newPassword])) {
                $success = '密码修改成功，请重新登录';
                // 强制登出
                adminLogout();
                header('Location: admin_login.php?login_expired=1');
                exit;
            } else {
                $error = '密码修改失败，请稍后重试';
            }
        }
    }
}

// 如果是登录请求，显示登录页面
if (isset($_GET['action']) && $_GET['action'] == 'login') {
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['username']) && !empty($_POST['password'])) {
        $username = trim($_POST['username']);
        $password = trim($_POST['password']);
        
        if (adminLogin($username, $password)) {
            header('Location: admin.php');
            exit;
        } else {
            $error = '用户名或密码错误';
        }
    }
    
    // 登录页面HTML
    ?>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>管理员登录 - 订单自主查询系统</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
                background-color: #f5f5f5;
                color: #333;
                line-height: 1.6;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
            }
            .login-container {
                background-color: white;
                border-radius: 10px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                padding: 40px;
                width: 100%;
                max-width: 400px;
            }
            .login-title {
                text-align: center;
                font-size: 24px;
                font-weight: bold;
                margin-bottom: 30px;
                color: #2c3e50;
            }
            .form-group {
                margin-bottom: 20px;
            }
            label {
                display: block;
                margin-bottom: 8px;
                font-weight: 500;
                color: #555;
            }
            input[type="text"],
            input[type="password"] {
                width: 100%;
                padding: 12px;
                font-size: 16px;
                border: 2px solid #e1e5e9;
                border-radius: 8px;
                transition: border-color 0.3s ease;
            }
            input[type="text"]:focus,
            input[type="password"]:focus {
                outline: none;
                border-color: #3498db;
            }
            .btn {
                background-color: #3498db;
                color: white;
                border: none;
                padding: 12px 20px;
                font-size: 16px;
                border-radius: 8px;
                cursor: pointer;
                transition: background-color 0.3s ease;
                width: 100%;
            }
            .btn:hover {
                background-color: #2980b9;
            }
            .error-message {
                background-color: #fee;
                color: #c62828;
                padding: 10px;
                border-radius: 8px;
                margin-bottom: 20px;
                text-align: center;
            }
            .footer {
                text-align: center;
                margin-top: 20px;
                color: #999;
                font-size: 12px;
            }
        </style>
    </head>
    <body>
        <div class="login-container">
            <div class="login-title">管理员登录</div>
            
            <?php if (!empty($error)): ?>
                <div class="error-message"><?php echo $error; ?></div>
            <?php endif; ?>
            
            <form method="post" action="admin.php?action=login">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" placeholder="请输入用户名" required>
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" placeholder="请输入密码" required>
                </div>
                <button type="submit" class="btn">登录</button>
            </form>
            
            <div class="footer">
                 © <?php echo date('Y'); ?> 订单自主查询系统 | 慕念科技
              </div>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// 后台管理页面HTML
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>慕念科技订单自助查询系统</title>
    <script>
        // 标题加密保护
        const originalTitle = document.title;
        const encryptedTitle = btoa(unescape(encodeURIComponent(originalTitle)));
        
        // 定期检查标题是否被篡改
        setInterval(function() {
            if (document.title !== originalTitle) {
                // 恢复原始标题
                document.title = originalTitle;
                console.log('检测到标题被篡改，已恢复！');
            }
        }, 1000);
        
        // 防止通过控制台修改
        Object.defineProperty(document, 'title', {
            set: function(newValue) {
                if (newValue !== originalTitle) {
                    console.warn('禁止修改页面标题！');
                    return;
                }
                Object.getOwnPropertyDescriptor(Object.getPrototypeOf(document), 'title').set.call(this, newValue);
            }
        });
    </script>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .header {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo {
            font-size: 24px;
            font-weight: bold;
            color: #3498db;
        }
        .logout-btn {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            text-decoration: none;
            font-size: 14px;
        }
        .logout-btn:hover {
            background-color: #c0392b;
        }
        
        /* 管理员信息 */
        .admin-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .admin-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            cursor: pointer;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            border: 2px solid #e1e5e9;
        }
        .admin-avatar:hover {
            transform: scale(1.1);
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }
        .admin-name {
            font-size: 14px;
            color: #555;
        }
        
        /* 弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        .modal-content {
            background-color: white;
            border-radius: 10px;
            padding: 30px;
            width: 100%;
            max-width: 500px;
            position: relative;
            animation: modalFadeIn 0.3s ease;
        }
        @keyframes modalFadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e1e5e9;
        }
        .modal-title {
            font-size: 20px;
            font-weight: bold;
            color: #2c3e50;
        }
        .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #999;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: background-color 0.3s ease;
        }
        .close-btn:hover {
            background-color: #f5f5f5;
        }
        
        .form-row {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }
        .form-row .form-group {
            flex: 1;
            margin-bottom: 0;
        }
        .section {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            padding: 30px;
            margin-bottom: 30px;
        }
        .section-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #2c3e50;
            padding-bottom: 10px;
            border-bottom: 2px solid #e1e5e9;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #555;
        }
        input[type="text"] {
            width: 100%;
            padding: 12px;
            font-size: 16px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            transition: border-color 0.3s ease;
        }
        input[type="text"]:focus {
            outline: none;
            border-color: #3498db;
        }
        .btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 12px 20px;
            font-size: 16px;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .btn:hover {
            background-color: #2980b9;
        }
        .btn-danger {
            background-color: #e74c3c;
        }
        .btn-danger:hover {
            background-color: #c0392b;
        }
        .error-message {
            background-color: #fee;
            color: #c62828;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #c62828;
        }
        .success-message {
            background-color: #efe;
            color: #2e7d32;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #2e7d32;
        }
        .table-container {
            overflow-x: auto;
            margin-top: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e1e5e9;
        }
        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #555;
        }
        tr:hover {
            background-color: #f8f9fa;
        }
        .tracking-numbers-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 8px;
        }
        .tracking-number-tag {
            background-color: #e3f2fd;
            color: #1976d2;
            padding: 4px 10px;
            border-radius: 4px;
            font-size: 14px;
            font-family: 'Courier New', monospace;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .tracking-number-delete {
            cursor: pointer;
            color: #e74c3c;
            font-weight: bold;
        }
        .add-tracking-btn {
            background-color: #2ecc71;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin-top: 10px;
        }
        .add-tracking-btn:hover {
            background-color: #27ae60;
        }
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            .section {
                padding: 20px;
            }
            .header {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="logo">订单自主查询系统 - 后台管理</div>
            <div class="admin-info">
                <a href="admin.php?action=logout" title="点击退出登录" onclick="return confirm('确定要退出登录吗？');">
                    <img id="adminAvatar" src="https://q1.qlogo.cn/g?b=qq&nk=<?php echo htmlspecialchars($adminInfo['admin_qq'] ?? ''); ?>&s=100" alt="管理员头像" class="admin-avatar" onerror="this.src='https://q1.qlogo.cn/g?b=qq&nk=0&s=100'">
                </a>
                <span class="admin-name"><?php echo htmlspecialchars($adminInfo['username'] ?? ''); ?></span>
            </div>
        </div>
        
        <?php if (!empty($error)): ?>
            <div class="error-message"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <?php if (!empty($success)): ?>
            <div class="success-message"><?php echo $success; ?></div>
        <?php endif; ?>
        
        <!-- 系统设置 -->
        <div class="section">
            <div class="section-title">系统设置</div>
            <form method="post" action="" enctype="multipart/form-data">
                <input type="hidden" name="action" value="update_settings">
                
                <!-- 阿里云API密钥 -->
                <div class="form-group">
                    <label for="api_key">阿里云API密钥</label>
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <input type="text" id="api_key" name="api_key" value="<?php echo htmlspecialchars($settings['api_key'] ?? ''); ?>" placeholder="请输入阿里云APPCODE" style="flex: 1;">
                        <a href="https://market.aliyun.com/detail/cmapi021863;jsessionid=71DC5E40EF9BE1C216674C45C02494B3#sku=yuncode15863000017" target="_blank" style="color: #1677ff; text-decoration: none;">前往申请</a>
                    </div>
                </div>
                
                <!-- 网站Logo -->
                <div class="form-group">
                    <label for="logo">网站Logo</label>
                    <div style="margin-bottom: 10px;">
                        <?php if (!empty($settings['logo'])): ?>
                            <img src="<?php echo htmlspecialchars($settings['logo']); ?>" alt="当前Logo" style="max-width: 200px; max-height: 100px;">
                        <?php else: ?>
                            <span>暂无Logo，前台将使用默认Logo</span>
                        <?php endif; ?>
                    </div>
                    <input type="file" id="logo" name="logo" accept="image/*">
                    <small style="color: #666;">支持JPG、PNG、GIF格式，建议尺寸不超过200x100像素</small>
                </div>
                
                <!-- 联系我们信息 -->
                <div class="form-group">
                    <h3 style="margin-bottom: 15px; color: #34495e;">联系我们信息</h3>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label for="contact_email">邮箱</label>
                            <input type="text" id="contact_email" name="contact_email" value="<?php echo htmlspecialchars($settings['contact_email'] ?? 'support@example.com'); ?>" placeholder="请输入联系邮箱">
                        </div>
                        <div class="form-group">
                            <label for="contact_phone">电话</label>
                            <input type="text" id="contact_phone" name="contact_phone" value="<?php echo htmlspecialchars($settings['contact_phone'] ?? '400-123-4567'); ?>" placeholder="请输入联系电话">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="contact_hours">工作时间</label>
                        <input type="text" id="contact_hours" name="contact_hours" value="<?php echo htmlspecialchars($settings['contact_hours'] ?? '周一至周五 9:00-18:00'); ?>" placeholder="请输入工作时间">
                    </div>
                </div>
                

                
                <button type="submit" class="btn">保存设置</button>
            </form>
        </div>
        
        <!-- 更改密码 -->
        <div class="section">
            <div class="section-title">更改密码</div>
            <form method="post" action="">
                <input type="hidden" name="action" value="change_password">
                <div class="form-group">
                    <label for="current_password">当前密码</label>
                    <input type="password" id="current_password" name="current_password" placeholder="请输入当前密码" required>
                </div>
                <div class="form-group">
                    <label for="new_password">新密码</label>
                    <input type="password" id="new_password" name="new_password" placeholder="请输入新密码" required>
                </div>
                <div class="form-group">
                    <label for="confirm_password">确认新密码</label>
                    <input type="password" id="confirm_password" name="confirm_password" placeholder="请再次输入新密码" required>
                </div>
                <button type="submit" class="btn">修改密码</button>
            </form>
        </div>
        
        <!-- 添加收件人 -->
        <div class="section">
            <div class="section-title">添加收件人</div>
            <form method="post" action="" id="addRecipientForm">
                <input type="hidden" name="action" value="add_recipient">
                <div class="form-group">
                    <label for="name">姓名</label>
                    <input type="text" id="name" name="name" placeholder="请输入收件人姓名" required>
                </div>
                <div class="form-group">
                    <label for="phone">手机号</label>
                    <input type="text" id="phone" name="phone" placeholder="请输入收件人手机号" required>
                </div>
                <div class="form-group">
                    <label for="order_number">订单号</label>
                    <input type="text" id="order_number" name="order_number" placeholder="请输入订单号">
                </div>
                <div class="form-group">
                    <label>快递单号</label>
                    <div id="trackingNumbersContainer">
                        <div class="tracking-input-group">
                            <input type="text" name="tracking_numbers[]" placeholder="请输入快递单号">
                        </div>
                    </div>
                    <button type="button" class="add-tracking-btn" id="addTrackingBtn">+ 添加更多快递单号</button>
                </div>
                <button type="submit" class="btn">添加收件人</button>
            </form>
        </div>
        
        <!-- 收件人列表 -->
        <div class="section">
            <div class="section-title">收件人列表</div>
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>姓名</th>
                            <th>手机号</th>
                            <th>订单号</th>
                            <th>快递单号</th>
                            <th>添加时间</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($recipients)): ?>
                                <?php foreach ($recipients as $recipient): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($recipient['name']); ?></td>
                                    <td><?php echo htmlspecialchars($recipient['phone']); ?></td>
                                    <td><?php echo htmlspecialchars($recipient['order_number'] ?? '无'); ?></td>
                                    <td>
                                        <?php if (!empty($recipient['tracking_numbers'])): ?>
                                            <div class="tracking-numbers-list">
                                                <?php foreach ($recipient['tracking_numbers'] as $trackingNumber): ?>
                                                    <div class="tracking-number-tag">
                                                        <?php echo htmlspecialchars($trackingNumber); ?>
                                                        <span class="tracking-number-delete" data-tracking="<?php echo htmlspecialchars($trackingNumber); ?>">×</span>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php else: ?>
                                            无
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo $recipient['created_at']; ?></td>
                                    <td>
                                        <form method="post" action="" style="display: inline;">
                                            <input type="hidden" name="action" value="delete_recipient">
                                            <input type="hidden" name="id" value="<?php echo $recipient['id']; ?>">
                                            <button type="submit" class="btn btn-danger" onclick="return confirm('确定要删除该收件人及其所有快递单号吗？');">删除</button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" style="text-align: center; color: #999;">暂无收件人信息</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                </table>
            </div>
        </div>
        
        <div style="text-align: center; color: #999; font-size: 12px; margin-top: 40px;">
             © <?php echo date('Y'); ?> 订单自主查询系统 | 慕念科技
          </div>
    </div>
    
    <!-- 删除快递单号表单 -->
    <form id="deleteTrackingForm" method="post" action="" style="display: none;">
        <input type="hidden" name="action" value="delete_tracking">
        <input type="hidden" name="tracking_number" id="deleteTrackingNumber">
    </form>
    
    <!-- 管理员信息修改弹窗 -->
    <div id="adminModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">修改管理员信息</h3>
                <button class="close-btn" onclick="closeModal()">&times;</button>
            </div>
            <form method="post" action="admin.php">
                <input type="hidden" name="action" value="update_admin">
                
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" value="<?php echo htmlspecialchars($adminInfo['username'] ?? ''); ?>" placeholder="请输入用户名" required>
                </div>
                
                <div class="form-group">
                    <label for="admin_qq">QQ号码</label>
                    <input type="text" id="admin_qq" name="admin_qq" value="<?php echo htmlspecialchars($adminInfo['admin_qq'] ?? ''); ?>" placeholder="请输入QQ号码">
                </div>
                
                <div class="form-group">
                    <label for="current_password">当前密码（修改密码时需要）</label>
                    <input type="password" id="current_password" name="current_password" placeholder="请输入当前密码">
                </div>
                
                <div class="form-group">
                    <label for="new_password">新密码（不修改密码则为空）</label>
                    <input type="password" id="new_password" name="new_password" placeholder="请输入新密码">
                </div>
                
                <div class="form-group">
                    <label for="confirm_password">确认新密码</label>
                    <input type="password" id="confirm_password" name="confirm_password" placeholder="请再次输入新密码">
                </div>
                
                <button type="submit" class="btn">保存修改</button>
            </form>
        </div>
    </div>

    <script src="../assets/js/script.js"></script>
    <script>
        // 检查登录失效提示
        <?php if ($loginExpired) { ?>
            alert('账号信息已变更，请重新登录');
        <?php } ?>
        
        // 弹窗相关函数
        function openModal() {
            document.getElementById('adminModal').style.display = 'flex';
        }
        
        function closeModal() {
            document.getElementById('adminModal').style.display = 'none';
        }
        
        // 点击头像弹窗功能已移除，现在点击头像直接退出登录
        
        
        // 点击弹窗外部关闭弹窗
        window.addEventListener('click', function(event) {
            const modal = document.getElementById('adminModal');
            if (event.target === modal) {
                closeModal();
            }
        });
        // 添加更多快递单号输入框
        document.getElementById('addTrackingBtn').addEventListener('click', function() {
            const container = document.getElementById('trackingNumbersContainer');
            const newInputGroup = document.createElement('div');
            newInputGroup.className = 'tracking-input-group';
            newInputGroup.innerHTML = `
                <input type="text" name="tracking_numbers[]" placeholder="请输入快递单号">
                <button type="button" class="remove-tracking-btn" style="margin-top: 5px; background-color: #e74c3c; color: white; border: none; padding: 4px 8px; border-radius: 4px; cursor: pointer;">删除</button>
            `;
            container.appendChild(newInputGroup);
            
            // 为新添加的删除按钮添加事件监听
            newInputGroup.querySelector('.remove-tracking-btn').addEventListener('click', function() {
                newInputGroup.remove();
            });
        });
        
        // 快递单号删除功能
        document.querySelectorAll('.tracking-number-delete').forEach(element => {
            element.addEventListener('click', function() {
                const trackingNumber = this.getAttribute('data-tracking');
                if (confirm(`确定要删除快递单号 ${trackingNumber} 吗？`)) {
                    document.getElementById('deleteTrackingNumber').value = trackingNumber;
                    document.getElementById('deleteTrackingForm').submit();
                }
            });
        });
        
        // 表单验证
        document.getElementById('addRecipientForm').addEventListener('submit', function(e) {
            const name = document.getElementById('name').value.trim();
            const phone = document.getElementById('phone').value.trim();
            
            if (!name || !phone) {
                alert('姓名和手机号不能为空');
                e.preventDefault();
                return;
            }
            
            // 简单的手机号格式验证
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phoneRegex.test(phone)) {
                alert('请输入正确的手机号码');
                e.preventDefault();
                return;
            }
        });
    </script>
</body>
</html>